<!DOCTYPE html><!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]--><!--[if gt IE 8]><!--><html class="no-js" lang="en"><!--<![endif]--><head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  
  <link rel="canonical" href="https://sequelize.org/v3/docs/docs/scopes/">
  <link rel="shortcut icon" href="/v3/favicon.ico">
  
  <title>Scopes - Sequelize | The Node.js / io.js ORM for PostgreSQL, MySQL, SQLite and MSSQL</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700|Roboto+Slab:400,700|Inconsolata:400,700">

  <link rel="stylesheet" href="/v3/css/theme.css">
  <link rel="stylesheet" href="/v3/css/theme_extra.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/github.min.css">
  <link href="/v3/css/custom.css" rel="stylesheet">
  
  <script>
    // Current page data
    var mkdocs_page_name = "Scopes";
    var mkdocs_page_input_path = "docs/scopes.md";
    var mkdocs_page_url = "/v3/docs/scopes/";
  </script>
  
  <script src="/v3/js/jquery-2.1.1.min.js" defer=""></script>
  <script src="/v3/js/modernizr-2.8.3.min.js" defer=""></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/highlight.min.js"></script>
  <script>hljs.initHighlightingOnLoad();</script> 
<meta name="robots" content="noindex"></head>

<body class="wy-body-for-nav" role="document">

  <div class="wy-grid-for-nav">

    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side stickynav">
    <div class="wy-side-scroll">
      <div class="wy-side-nav-search">
        <a href="/v3" class="icon icon-home"> Sequelize | The Node.js / io.js ORM for PostgreSQL, MySQL, SQLite and MSSQL</a>
        <div role="search">
  <form id="rtd-search-form" class="wy-form" action="/v3/search.html" method="get">
      <input type="text" name="q" placeholder="Search docs" title="Type search term here">
  </form>
</div>
      </div>

      <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="/v3">Home</a>
                    </li>
                </ul>
                <p class="caption"><span class="caption-text">Documentation</span></p>
                <ul class="current">
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/getting-started/">Getting Started</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/schema/">Working with table schemas</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="#">Models</a>
    <ul>
                <li class="toctree-l2"><a class="reference internal" href="/v3/docs/models-definition/">Definition</a>
                </li>
                <li class="toctree-l2"><a class="reference internal" href="/v3/docs/models-usage/">Usage</a>
                </li>
    </ul>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/querying/">Querying</a>
                    </li>
                    <li class="toctree-l1 current"><a class="reference internal current" href="./">Scopes</a>
    <ul class="current">
    </ul>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/instances/">Instances</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/associations/">Relations / Associations</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/hooks/">Hooks</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/transactions/">Transactions</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/legacy/">Working with legacy tables</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/raw-queries/">Raw queries</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/migrations/">Migrations</a>
                    </li>
                </ul>
                <p class="caption"><span class="caption-text">API</span></p>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/sequelize/">Sequelize</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/model/">Model</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/instance/">Instance</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="#">Associations</a>
    <ul>
                <li class="toctree-l2"><a class="reference internal" href="/v3/api/associations/">Overview</a>
                </li>
                <li class="toctree-l2"><a class="reference internal" href="/v3/api/associations/belongs-to/">BelongsTo (1:1)</a>
                </li>
                <li class="toctree-l2"><a class="reference internal" href="/v3/api/associations/has-one/">HasOne (1:1)</a>
                </li>
                <li class="toctree-l2"><a class="reference internal" href="/v3/api/associations/has-many/">HasMany (1:m)</a>
                </li>
                <li class="toctree-l2"><a class="reference internal" href="/v3/api/associations/belongs-to-many/">BelongsToMany (n:m)</a>
                </li>
    </ul>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/hooks/">Hooks</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/transaction/">Transaction</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/datatypes/">Datatypes</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/deferrable/">Deferrable</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/errors/">Errors</a>
                    </li>
                </ul>
                <p class="caption"><span class="caption-text">Misc</span></p>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/changelog/">Changelog</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/imprint/">Imprint</a>
                    </li>
                </ul>
      </div>
    </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" role="navigation" aria-label="top navigation">
        <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
        <a href="/v3">Sequelize | The Node.js / io.js ORM for PostgreSQL, MySQL, SQLite and MSSQL</a>
      </nav>

      
      <div class="wy-nav-content">
        <div class="rst-content">
          <div role="navigation" aria-label="breadcrumbs navigation">
  <ul class="wy-breadcrumbs">
    <li><a href="/v3">Docs</a> »</li>
    
      
        
          <li>Documentation »</li>
        
      
    
    <li>Scopes</li>
    <li class="wy-breadcrumbs-aside">
      
        <a href="https://github.com/sequelize/sequelize/edit/master/docs/docs/scopes.md" class="icon icon-github"> Edit on GitHub</a>
      
    </li>
  </ul>
  
  <hr>
</div>

          <div role="main">
            <div class="section">
              
                <h1 id="definition">Definition</h1>
<p>Scoping allows you to define commonly used queries that you can easily use later. Scopes can include all the same attributes as regular finders, <code>where</code>, <code>include</code>, <code>limit</code> etc.</p>
<p>Scopes are defined in the model definition and can be finder objects, or functions returning finder objects - except for the default scope, which can only be an object:</p>
<pre><code class="language-js">var Project = sequelize.define('project', {
  // Attributes
}, {
  defaultScope: {
    where: {
      active: true
    }
  },
  scopes: {
    deleted: {
      where: {
        deleted: true
      }
    },
    activeUsers: {
      include: [
        { model: User, where: { active: true }}
      ]
    }
    random: function () {
      return {
        where: {
          someNumber: Math.random()
        }
      }
    },
    accessLevel: function (value) {
      return {
        where: {
          accessLevel: {
            $gte: value
          }
        }
      }
    }
  }
});
</code></pre>
<p>You can also add scopes after a model has been defined by calling <code>addScope</code>. This is especially useful for scopes with includes, where the model in the include might not be defined at the time the other model is being defined.</p>
<p>The default scope is always applied. This means, that with the model definition above, <code>Project.findAll()</code> will create the following query:</p>
<pre><code class="language-sql">SELECT * FROM projects WHERE active = true
</code></pre>
<p>The default scope can be removed by calling <code>.unscoped()</code>, <code>.scope(null)</code>, or by invoking another scope:</p>
<pre><code class="language-js">Project.scope('deleted').findAll(); // Removes the default scope
</code></pre>
<pre><code class="language-sql">SELECT * FROM projects WHERE deleted = true
</code></pre>
<h1 id="usage">Usage</h1>
<p>Scopes are applied by calling <code>.scope</code> on the model definition, passing the name of one or more scopes. <code>.scope</code> returns a fully functional model instance with all the regular methods: <code>.findAll</code>, <code>.update</code>, <code>.count</code>, <code>.destroy</code> etc. You can save this model instance and reuse it later:</p>
<pre><code class="language-js">var DeletedProjects = Project.scope('deleted');

DeletedProjects.findAll();
// some time passes

// let's look for deleted projects again!
DeletedProjects.findAll();
</code></pre>
<p>Scopes apply to <code>.find</code>, <code>.findAll</code>, <code>.count</code>, <code>.update</code> and <code>.destroy</code>.</p>
<p>Scopes which are functions can be invoked in two ways. If the scope does not take any arguments it can be invoked as normally. If the scope takes arguments, pass an object:</p>
<pre><code class="language-js">Project.scope('random', { method: ['accessLevel', 19]}).findAll();
</code></pre>
<pre><code class="language-sql">SELECT * FROM projects WHERE someNumber = 42 AND accessLevel &gt;= 19
</code></pre>
<h2 id="merging">Merging</h2>
<p>Several scopes can be applied simultaneously by passing an array of scopes to <code>.scope</code>, or by passing the scopes as consecutive arguments.</p>
<pre><code class="language-js">// These two are equivalent
Project.scope('deleted', 'activeUsers').findAll();
Project.scope(['deleted', 'activeUsers']).findAll();
</code></pre>
<pre><code class="language-sql">SELECT * FROM projects
INNER JOIN users ON projects.userId = users.id
AND users.active = true
</code></pre>
<p>If you want to apply another scope alongside the default scope, pass the key <code>defaultScope</code> to <code>.scope</code>:</p>
<pre><code class="language-js">Project.scope('defaultScope', 'deleted').findAll();
</code></pre>
<pre><code class="language-sql">SELECT * FROM projects WHERE active = true AND deleted = true
</code></pre>
<p>When invoking several scopes, keys from subsequent scopes will overwrite previous ones (similar to <a href="https://lodash.com/docs#assign">_.assign</a>). Consider two scopes:</p>
<pre><code class="language-js">{
  scope1: {
    where: {
      firstName: 'bob',
      age: {
        $gt: 20
      }
    },
    limit: 2
  },
  scope2: {
    where: {
      age: {
        $gt: 30
      }
    },
    limit: 10
  }
}
</code></pre>
<p>Calling <code>.scope('scope1', 'scope2')</code> will yield the following query</p>
<pre><code class="language-sql">WHERE firstName = 'bob' AND age &gt; 30 LIMIT 10
</code></pre>
<p>Note how <code>limit</code> and <code>age</code> are overwritten by <code>scope2</code>, while <code>firstName</code> is preserved. <code>limit</code>, <code>offset</code>, <code>order</code>, <code>paranoid</code>, <code>lock</code> and <code>raw</code> are overwritten, while <code>where</code> and <code>include</code> are shallowly merged. This means that identical keys in the where objects, and subsequent includes of the same model will both overwrite each other.</p>
<p>The same merge logic applies when passing a find object directly to findAll on a scoped model:</p>
<pre><code class="language-js">Project.scope('deleted').findAll({
  where: {
    firstName: 'john'
  }
})
</code></pre>
<pre><code class="language-sql">WHERE deleted = true AND firstName = 'john'
</code></pre>
<p>Here the <code>deleted</code> scope is merged with the finder. If we were to pass <code>where: { firstName: 'john', deleted: false }</code> to the finder, the <code>deleted</code> scope would be overwritten.</p>
<h1 id="associations">Associations</h1>
<p>Sequelize has two different but related scope concepts in relation to associations. The difference is subtle but important:</p>
<ul>
<li><strong>Association scopes</strong> Allow you to specify default attributes when getting and setting associations - useful when implementing polymorphic associations. This scope is only invoked on the association between the two models, when using the <code>get</code>, <code>set</code>, <code>add</code> and <code>create</code> associated model functions</li>
<li><strong>Scopes on associated models</strong> Allows you to apply default and other scopes when fetching associations, and allows you to pass a scoped model when creating associations. These scopes both apply to regular finds on the model and to find through the association.</li>
</ul>
<p>As an example, consider the models Post and Comment. Comment is associated to several other models (Image, Video etc.) and the association between Comment and other models is polymorphic, which means that Comment stores a <code>commentable</code> column, in addition to the foreign key <code>commentable_id</code>.</p>
<p>The polymorphic association can be implemented with an <em>association scope</em> :</p>
<pre><code class="language-js">this.Post.hasMany(this.Comment, {
  foreignKey: 'commentable_id',
  scope: {
    commentable: 'post'
  }
});
</code></pre>
<p>When calling <code>post.getComments()</code>, this will automatically add <code>WHERE commentable = 'post'</code>. Similarly, when adding new comments to a post, <code>commentable</code> will automagically be set to <code>'post'</code>. The association scope is meant to live in the background without the programmer having to worry about it - it cannot be disabled. For a more complete polymorphic example, see <a href="./associations/#scopes">Association scopes</a></p>
<p>Consider then, that Post has a default scope which only shows active posts: <code>where: { active: true }</code>. This scope lives on the associated model (Post), and not on the association like the <code>commentable</code> scope did. Just like the default scope is applied when calling <code>Post.findAll()</code>, it is also applied when calling <code>User.getPosts()</code> - this will only return the active posts for that user.</p>
<p>To disable the default scope, pass <code>scope: null</code> to the getter: <code>User.getPosts({ scope: null })</code>. Similarly, if you want to apply other scopes, pass an array like you would to <code>.scope</code>:</p>
<pre><code class="language-js">User.getPosts({ scope: ['scope1', 'scope2']});
</code></pre>
<p>If you want to create a shortcut method to a scope on an associated model, you can pass the scoped model to the association. Consider a shortcut to get all deleted posts for a user:</p>
<pre><code class="language-js">var Post = sequelize.define('post', attributes, {
  defaultScope: {
    where: {
      active: true
    }
  },
  scopes: {
    deleted: {
      where: {
        deleted: true
      }
    }
  }
});

User.hasMany(Post); // regular getPosts association
User.hasMany(Post.scope('deleted'), { as: 'deletedPosts' });

</code></pre>
<pre><code class="language-js">User.getPosts(); // WHERE active = true
User.getDeletedPosts(); // WHERE deleted = true
</code></pre>
              
            </div>
          </div>
          <footer>
  
    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
        <a href="/v3/docs/instances/" class="btn btn-neutral float-right" title="Instances">Next <span class="icon icon-circle-arrow-right"></span></a>
      
      
        <a href="/v3/docs/querying/" class="btn btn-neutral" title="Querying"><span class="icon icon-circle-arrow-left"></span> Previous</a>
      
    </div>
  

  <hr>

  <div role="contentinfo">
    <!-- Copyright etc -->
    
  </div>

  Built with <a href="https://www.mkdocs.org/">MkDocs</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
      
        </div>
      </div>

    </section>

  </div>

  <div class="rst-versions" role="note" aria-label="versions">
  <span class="rst-current-version" data-toggle="rst-current-version">
    
        <span>
          <a href="https://github.com/sequelize/sequelize/" class="fa fa-github" style="color: #fcfcfc"> GitHub</a>
        </span>
    
    
      <span><a href="/v3/docs/querying/" style="color: #fcfcfc">« Previous</a></span>
    
    
      <span><a href="/v3/docs/instances/" style="color: #fcfcfc">Next »</a></span>
    
  </span>
</div>
    <script>var base_url = '../..';</script>
    <script src="/v3/js/theme_extra.js" defer=""></script>
    <script src="/v3/js/theme.js" defer=""></script>
      <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js" defer=""></script>
      <script src="/v3/search/main.js" defer=""></script>
    <script defer="">
        window.onload = function () {
            SphinxRtdTheme.Navigation.enable(true);
        };
    </script>



</body></html>